//
//  MYXUpdataconfigurator.m
//  meiyinxiang
//
//  Created by 陈李飞 on 2017/11/8.
//  Copyright © 2017年 hbjApple. All rights reserved.
//

#import "MYXUpdataconfigurator.h"
#import "VPImageCropperViewController.h"
#import "JXTActionSheet.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "MYYAuthenticationCell.h"
#import "UIImage+fixOrientation.h"
#import "MYYChangeInforViewController.h"
#import "MYXPhotoauthenticationViewController.h"

#define kWith_W      80
#define ORIGINAL_MAX_WIDTH 640.0f


@interface MYXUpdataconfigurator()<UIAlertViewDelegate,UIGestureRecognizerDelegate,VPImageCropperDelegate,UINavigationControllerDelegate,JXTActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong)UIViewController *ChanInfor;


@end
@implementation MYXUpdataconfigurator
- (void)setup:(UIViewController *)vc type:(int)type{
    
    if (type==1) {
        _ChanInfor =[[MYYChangeInforViewController  alloc]init];
        _ChanInfor = vc;
    }else if (type==2){
        _ChanInfor =[[MYXPhotoauthenticationViewController  alloc]init];
        _ChanInfor = vc;
    }
   
    //弹出选择框，是选择拍摄还是直接从相片中选取
    NSArray *array = [[NSArray alloc] initWithObjects:@"拍照",@"从相册选取", nil];
    JXTActionSheet *actionSheet = [[JXTActionSheet alloc] initWithTitle:nil buttonTitles:array redButtonIndex:-1 delegate:self];
    [actionSheet show];
}


-(void)actionSheet:(JXTActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //拍照
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [_ChanInfor presentViewController:imagePicker animated:YES completion:nil];
    }else if (buttonIndex == 1){
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [_ChanInfor presentViewController:imagePicker animated:YES completion:nil];
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    portraitImg = [self imageByScalingToMaxSize:portraitImg];
    // 裁剪
    VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f,WIDTH, HEIGHT) limitScaleRatio:3.0];
    imgEditorVC.delegate = self;
    [_ChanInfor presentViewController:imgEditorVC animated:YES completion:nil];
}

- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:NO completion:nil];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
-(void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage
{
    [cropperViewController dismissViewControllerAnimated:NO completion:^{
        NSLog(@"请求服务器");
        [self updateAvatar:editedImage];
    }];
}

-(void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController
{
    [cropperViewController dismissViewControllerAnimated:NO completion:nil];
}

-(void)updateAvatar:(UIImage *)image
{
    
    [[Http sharedInstance] uploadDataWithUrl:MYY_upload_URL withParams:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // UIImage *img = [image fixOrientation];
        NSData *imgscreenData = UIImageJPEGRepresentation(image, 0.2);
        [formData appendPartWithFileData:imgscreenData name:@"file" fileName:@"pic.jpg" mimeType:@"image/jpg"];
    } completion:^(id data, NSError *error) {
        int  nRet = [[data objectForKey:@"status"] intValue];
        if (nRet == 1) {
            NSString *imageData =[data objectForKey:@"data"];
            if (self.SucessBlock) {
                self.SucessBlock(imageData,image);
            }
        }
    }];
    
    
    
}
@end
